package net.xdclass.interceptor;

import io.jsonwebtoken.Claims;
import lombok.extern.slf4j.Slf4j;
import net.xdclass.enums.BizCodeEnum;
import net.xdclass.model.LoginUser;
import net.xdclass.util.CommonUtil;
import net.xdclass.util.JsonData;
import net.xdclass.util.JwtUtil;
import org.apache.commons.lang3.StringUtils;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * @Classname LoginInterceptor
 * @Description TODO
 * @Date 2022/4/19 11:12
 * @Created by sunhao
 */
@Slf4j
public class LoginInterceptor implements HandlerInterceptor {

  public static ThreadLocal<LoginUser> threadLocal = new ThreadLocal<>();

  @Override
  public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
    String accessToken = request.getHeader("token");
    if(accessToken == null){
      accessToken = request.getParameter("token");
    }
    if(StringUtils.isEmpty(accessToken)){
      CommonUtil.sendJsonMessage(response, JsonData.buildResult(BizCodeEnum.ACCOUNT_NOT_LOGIN));
      return false;
    }
    Claims claims = JwtUtil.checkJwt(accessToken);
    if(claims == null){
      CommonUtil.sendJsonMessage(response, JsonData.buildResult(BizCodeEnum.ACCOUNT_NOT_LOGIN));
      return false;
    }
    LoginUser loginUser = LoginUser.transformation(claims);
    //1:通过 attribute传递
    request.setAttribute("loginUser",loginUser);
    //2:通过 threadLocal传递
    threadLocal.set(loginUser);
    return true;
  }


  @Override
  public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
    threadLocal.remove();
  }
}
